<?php

/**
 * Description of Adapter
 *
 * @author neozilon
 */
class Nosql_Auth_Adapter implements Zend_Auth_Adapter_Interface {

    const NOT_FOUND_MSG = "Cuenta Incorrecta";
    const INVALID_PASSWD_MSG = "Contraseña Invalida";

  /**
     *
     * @var Nosql_Model_User
     */
    protected $user;

    /**
        * @var string
        */
    protected $username;

    /**
        * @var string
        */
    
    protected $password;

    public function  __construct($username, $password) {
        $this->password = $password;
        $this->username = $username;
    }

    /**
        * Autenticacion
        *
        * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
        * @return Zend_Auth_Result
     */
    public function authenticate(){
        try{
            $this->user = Nosql_Model_Mysql_User::authenticate($this->username, md5($this->password) );
        }
        catch (Exception $e){
            if ($e->getCode() == Nosql_Model_Mysql_User::INVALID_PASSWD)
                return $this->result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, self::INVALID_PASSWD_MSG);
            if ($e->getCode() == Nosql_Model_Mysql_User::NOT_FOUND)
                return $this->result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, self::NOT_FOUND_MSG);
            else
                return $this->result(Zend_Auth_Result::FAILURE, "No ha sido posible autenticar el usuario, intente mas tarde");
        }
        
        return $this->result(Zend_Auth_Result::SUCCESS);
    
    }

    /**
     * Factory for Zend_Auth_Result
     *
     *@param integer    The Result code, see Zend_Auth_Result
     *@param mixed      The Message, can be a string or array
     *@return Zend_Auth_Result
     */
    public function result($code, $messages = array()) {
        //Zend_Debug::dump($messages);
        if (!is_array($messages)) {
            $messages = array($messages);
        }

        if ( $code == Zend_Auth_Result::SUCCESS){
            $user = new stdClass();
            $user->email = $this->user->email;
            $user->fullname = $this->user->fullname;
            $user->userid = $this->user->userid;
            $user->role = $this->user->role;
            $user->username = $this->user->username;
        }else{
            $user = null;
        }
        $this->user = null;
        return new Zend_Auth_Result($code, $user, $messages);
    }
}